/**
 * author wen
 * cunyu
 * email wjd_13@hotmail.com
 */
package com.cunyu.service;

import org.springframework.stereotype.Service;

import javax.management.relation.Role;
import java.util.List;
import java.util.Map;

/**
 * 权限信息
 * @author win
 * 2019/04/19-14:49
 */
@Service
public class RoleGroupService extends BaseService{

    /**
     * 2 条 sql
     *  String cancelSql = "update muserrole set role = replace(role,?,'')  where tid = ?" ;
     *  String addExdSql = "update muserrole set role = role || ?  where tid = ? and id in ("+id+") " ;
     */

    public List<Map<String, Object>> getGroups() {
        List<Map<String, Object>> roles = getList("select role,gname from mgroup order by role");
        return roles ;
    }

    public int updateGroup(String role, String[] id ,String name) {
        String sql = "update mgroup set gname = ? where role = ? " ;
        exec(sql,name,Integer.valueOf(role));
        String cancelSql = "update muserrole set role = replace(role,?,'') " ;
        exec(cancelSql,"["+role+"]");
        if(id!= null && id.length > 0){
            String addExdSql = "update muserrole set role = role || ?  where id in ("+ids(id)+") " ;
            exec(addExdSql,"["+role+"]");
        }
        return Integer.valueOf(role) ;
    }

    public int newGroup(String name, String[] id) {
        String max = "select max(role) from mgroup " ;
        int v = getInt(max);

        String sql = "insert into mgroup (role,gname) values (?,?)" ;
        int insert = insert(sql, v ,name);
        if(id.length > 0){
            String addExdSql = "update muserrole set role = role || ?  where id in ("+ids(id)+") " ;
            exec(addExdSql, "["+insert+"]");
        }
        return insert ;
    }

    private String ids (String[] id ){
        StringBuilder bu = new StringBuilder() ;
        for (String i : id){
            bu.append(i).append(",") ;
        }
        StringBuilder builder = bu.deleteCharAt(bu.length() - 1);
        return builder.toString();
    }

    /**
     * 删除权限相关数据
     */
    public void del(String role) {
        String users = "select count( *) from muser where role = ? " ;
        int count = getInt(users, Integer.valueOf(role));
        if(count > 0)
            return;

        String sql = "delete from mgroup where role = ? " ;
        String cancelSql = "update muserrole set role = replace(role,?,'') " ;
        exec(sql,Integer.valueOf(role)) ;
        exec(cancelSql,"["+role+"]");
    }
}
